package system

//针对前端用户的接口，复用管理员接口，默认角色为普通用户

import (
	"encoding/json"
	"time"

	"LRAdminServer/global"
	client "LRAdminServer/model/clientInfo"
	"LRAdminServer/model/common/response"
	"LRAdminServer/model/system"
	systemReq "LRAdminServer/model/system/request"
	systemRes "LRAdminServer/model/system/response"
	"LRAdminServer/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// Login
// @Tags     Base
// @Summary  普通用户邮箱登录 APP和前端用户
// @Produce   application/json
// @Param    data  body      systemReq.LoginCommonEmail                                             true  "邮箱, 密码, 验证码"
// @Success  200   {object}  response.Response{data=systemRes.EmailLoginResponse,msg=string}  "返回包括用户信息,token,过期时间"
// @Router   /user/login_email [post]
func (b *BaseApi) LoginCommonEmail(c *gin.Context) {
	var l systemReq.LoginCommonEmail
	err := c.ShouldBindJSON(&l)
	key := c.ClientIP()

	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(l, utils.LoginEmailVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	//判断登录的版本是否有效
	loginClient := client.ClientPlatform{AppId: l.AppId, Version: l.Version, Platform: &l.Platform}
	resultInfo, clientErr := clientInfoService.CheckClientPlatform(loginClient)
	if clientErr != nil || !(len(resultInfo.AppId) > 0) {
		response.FailWithMessage("版本太低，请先更新版本", c)
		return
	}

	// 判断验证码是否开启
	openCaptcha := global.GVA_CONFIG.Captcha.OpenCaptcha               // 是否开启防爆次数
	openCaptchaTimeOut := global.GVA_CONFIG.Captcha.OpenCaptchaTimeOut // 缓存超时时间
	v, ok := global.BlackCache.Get(key)
	if !ok {
		global.BlackCache.Set(key, 1, time.Second*time.Duration(openCaptchaTimeOut))
	}

	var oc bool = openCaptcha == 0 || openCaptcha < interfaceToInt(v)

	if !oc {
		u := &system.SysUser{Email: l.Email, Password: l.Password}
		user, err := userService.EmailLogin(u)
		if err != nil {
			global.GVA_LOG.Error("登陆失败! 用户名不存在或者密码错误!", zap.Error(err))
			// 验证码次数+1
			global.BlackCache.Increment(key, 1)
			response.FailWithMessage("用户名不存在或者密码错误", c)
			return
		}
		if user.Enable != 1 {
			global.GVA_LOG.Error("登陆失败! 用户被禁止登录!")
			// 验证码次数+1
			global.BlackCache.Increment(key, 1)
			response.FailWithMessage("用户被禁止登录", c)
			return
		}

		b.TokenNext(c, *user, true, loginClient)
		return
	}
	// 登录次数+1
	global.BlackCache.Increment(key, 1)
	response.FailWithMessage("登录失败", c)
}

// Register
// @Tags     CommonUser
// @Summary  普通用户注册账号 APP和前端用户
// @Produce   application/json
// @Param    data  body      systemReq.RegisterCommonEmail                                            true  "邮箱, 密码"
// @Success  200   {object}  response.Response{data=systemRes.SysUserResponse,msg=string}  "用户注册账号,返回包括用户信息"
// @Router   /user/register_email [post]
func (b *BaseApi) RegisterCommonEmail(c *gin.Context) {
	var r systemReq.RegisterCommonEmail
	err := c.ShouldBindJSON(&r)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(r, utils.RegisterEmailVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	//check email code

	codeValid := EmailStore.Verify(r.Email, r.Code, true)

	if !codeValid {
		response.FailWithMessage("验证码错误", c)
		return
	}

	var authorities []system.SysAuthority
	authorityIds := []uint{111}
	for _, v := range authorityIds {
		authorities = append(authorities, system.SysAuthority{
			AuthorityId: v,
		})
	}
	user := &system.SysUser{Username: r.Email, NickName: r.Email, Password: r.Password, AuthorityId: 111, Authorities: authorities, Enable: 1, Email: r.Email}

	userReturn, err := userService.EmailRegister(*user)

	if err != nil {
		global.GVA_LOG.Error("service register err", zap.Error(err))
		errMsg := "注册失败:" + err.Error()
		response.FailWithMessage(errMsg, c)
		return
	}

	jsonUser, mErr := json.Marshal(userReturn)

	if mErr != nil {
		global.GVA_LOG.Error("user Marshal err", zap.Error(err))
		response.FailWithMessage("注册失败", c)
		return
	}

	var respUser systemRes.EmailLoginUser
	uErr := json.Unmarshal(jsonUser, &respUser)
	if uErr != nil {
		global.GVA_LOG.Error("user UN Marshal err", zap.Error(err))
		response.FailWithMessage("注册失败", c)
		return
	}

	response.OkWithDetailed(gin.H{"user": respUser}, "注册成功", c)
}

// ResetPasswordEmail
// @Tags      CommonUser
// @Summary   重置用户密码
// @Security  ApiKeyAuth
// @Produce  application/json
// @Param     data  body      system.ResetPasswordEmail                 true  "ID"
// @Success   200   {object}  response.Response{msg=string}  "重置用户密码"
// @Router    /user/resetPasswordByEmail [post]
func (b *BaseApi) ResetPasswordEmail(c *gin.Context) {
	var req systemReq.ResetPasswordEmail
	err := c.ShouldBindJSON(&req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	codeValid := EmailStore.Verify(req.Email, req.Code, true)
	if !codeValid {
		response.FailWithMessage("验证码错误", c)
		return
	}
	user := system.SysUser{Email: req.Email, Password: req.Password}
	_, err = userService.ResetPasswordByNewPwd(user)

	if err != nil {
		global.GVA_LOG.Error("重置失败!", zap.Error(err))
		response.FailWithMessage("重置失败"+err.Error(), c)
		return
	}
	response.OkWithMessage("重置成功", c)
}

// GetUserInfo
// @Tags      CommonUser
// @Summary   获取用户信息
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Success   200  {object}  response.Response{data=map[string]interface{},msg=string}  "获取用户信息"
// @Router    /user/getCommonUserInfo [get]
func (b *BaseApi) GetCommonUserInfo(c *gin.Context) {
	uuid := utils.GetUserUuid(c)
	ReqUser, err := userService.GetCommonUserInfo(uuid)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}

	jsonUser, err := json.Marshal(ReqUser)

	if err != nil {
		global.GVA_LOG.Error("userinfo Marshal err!", zap.Error(err))
		response.FailWithMessage("用户信息获取失败", c)
		return
	}

	var respUser systemRes.EmailLoginUser
	uErr := json.Unmarshal(jsonUser, &respUser)
	if uErr != nil {
		global.GVA_LOG.Error("userinfo Unmarshal err!", zap.Error(err))
		response.FailWithMessage("用户信息获取失败", c)
		return
	}

	response.OkWithDetailed(gin.H{"userInfo": respUser}, "获取成功", c)
}

// SetSelfInfo
// @Tags      CommonUser
// @Summary   设置用户信息
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      system.ChangeCommonUserInfo                                            true  "用户名, 昵称"
// @Success   200   {object}  response.Response{data=map[string]interface{},msg=string}  "设置用户信息"
// @Router    /user/setCommonUserInfo [put]
func (b *BaseApi) SetCommonUserSelfInfo(c *gin.Context) {

	nickName := c.Request.FormValue("nickName")
	phone := c.Request.FormValue("phone")

	fileUrl := ""

	_, FileHeader, err := c.Request.FormFile("file")

	//有文件上传
	if err == nil {
		file, uploadErr := fileUploadAndDownloadService.UploadFile(FileHeader, "1") // 文件上传后拿到文件路径
		if uploadErr == nil {
			fileUrl = file.Url
		} else {
			global.GVA_LOG.Error("保存头像文件失败", zap.Error(err))
		}
	}

	var user systemReq.ChangeCommonUserInfo

	user.NickName = nickName
	user.Phone = phone
	userID := utils.GetUserID(c)
	err = userService.SetSelfInfo(system.SysUser{
		GVA_MODEL: global.GVA_MODEL{
			ID: userID,
		},
		NickName:  user.NickName,
		Phone:     user.Phone,
		HeaderImg: fileUrl,
	})
	if err != nil {
		global.GVA_LOG.Error("设置失败!", zap.Error(err))
		response.FailWithMessage("设置失败", c)
		return
	}
	response.OkWithMessage("设置成功", c)
}
